window.addEventListener('load', e => {
  const canvas = document.getElementById('canvas');
  const gl = getWebGLContext(canvas);
  initShaders(gl, v_shader_source, f_shader_source);

  gl.clearColor(0.0, 0.0, 0.0, 1.0);
  gl.clear(gl.COLOR_BUFFER_BIT);
  let position = new Float32Array([
    0.0, 2.5, -5.0, 0.4, 1.0, 0.4, // The green triangle
    -2.5, -2.5, -5.0, 0.4, 1.0, 0.4,
    2.5, -2.5, -5.0, 1.0, 0.4, 0.4,

    0.0, 3.0, -5.0, 1.0, 0.4, 0.4, // The yellow triagle
    -3.0, -3.0, -5.0, 1.0, 1.0, 0.4,
    3.0, -3.0, -5.0, 1.0, 1.0, 0.4,
  ]);
  let FSIZE = position.BYTES_PER_ELEMENT;

  let vertexBuffer = gl.createBuffer();
  gl.bindBuffer(gl.ARRAY_BUFFER, vertexBuffer);
  gl.bufferData(gl.ARRAY_BUFFER, position, gl.STATIC_DRAW);

  let a_Position = gl.getAttribLocation(gl.program, 'a_Position');
  gl.vertexAttribPointer(a_Position, 3, gl.FLOAT, false, 6 * FSIZE, 0);
  gl.enableVertexAttribArray(a_Position);

  let a_Color = gl.getAttribLocation(gl.program, 'a_Color');
  gl.vertexAttribPointer(a_Color, 3, gl.FLOAT, false, 6 * FSIZE, 3 * FSIZE);
  gl.enableVertexAttribArray(a_Color);

  let projMatrix = new Matrix4();
  projMatrix.setPerspective(30, canvas.width / canvas.height, 1, 100);
  projMatrix.lookAt(0, 0, 5, 0, 0, -100, 0, 1, 0);
  let u_ProjMatrix = gl.getUniformLocation(gl.program, 'u_ProjMatrix');
  gl.uniformMatrix4fv(u_ProjMatrix, false, new Matrix4(projMatrix).translate(-0.75, 0, 0).elements);
  gl.enable(gl.POLYGON_OFFSET_FILL);
  gl.drawArrays(gl.TRIANGLES, 0, 3);
  gl.polygonOffset(1.0, 1.0);
  gl.drawArrays(gl.TRIANGLES, 3, 3);
  // gl.uniformMatrix4fv(u_ProjMatrix, false, new Matrix4(projMatrix).translate(0.75, 0, 0).elements);
  // gl.drawArrays(gl.TRIANGLES, 0, 9);
});

const v_shader_source = `
  attribute vec4 a_Position;
  attribute vec4 a_Color;
  uniform mat4 u_ProjMatrix;
  varying vec4 v_Color;
  void main(){
    gl_Position = u_ProjMatrix * a_Position;
    v_Color = a_Color;
  }
`;

const f_shader_source = `
  precision lowp float;
  varying vec4 v_Color;
  void main(){
    gl_FragColor = v_Color;
  }
`;